package com.mes.schedule.dao;

import org.springframework.stereotype.Repository;

import com.mes.basicdata.dao.OperationDao;
import com.mes.basicdata.dao.WorkCenterDao;
import com.mes.common.dao.BasicDao;
import com.mes.common.exception.db.BaseDBException;
import com.mes.common.spring.SpringUtils;
import com.mes.common.util.IdentityGenerator;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.naming.NamingException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.mes.schedule.dao.iface.ISTaskDao;
import com.mes.schedule.domain.SCoTask;
import com.mes.schedule.domain.SOperationLink;
import com.mes.schedule.domain.SOperationTask;
import com.mes.schedule.domain.SParallelGroup;
import com.mes.schedule.domain.SPartTask;
import com.mes.schedule.domain.SSerialGroup;
import com.mes.schedule.domain.STask;
import com.mes.schedule.domain.STempOperationTask;
import com.mes.schedule.domain.ScheduleScheme;
import com.mes.schedule.manager.ScheduleLinkManager;
import com.mes.schedule.manager.ScheduleOperationTaskManager;
import com.mes.schedule.mm.DBHandler;
import com.mes.task.dao.PartTaskDao;

@Repository
public class STaskDao extends BasicDao<STask> implements ISTaskDao{
	private static final Log log = LogFactory.getLog(STaskDao.class);
	
	@Resource
	private SPartTaskDao schedulePartTaskDao = new SPartTaskDao();
	@Resource
	private DemandSTaskLinkDao demandSTaskLinkDao = new DemandSTaskLinkDao();
	@Resource
	private PartTaskDao partTaskDao = new PartTaskDao();
	@Resource
	private SOperationTaskDao sOperationTaskDao;
	@Resource
	private WorkCenterDao workCenterDao;
	@Resource
	private OperationDao operationDao;
	@Resource
	private SOperationLinkDao sOperationLinkDao;

	
	/**
	 * @see the method use for ScheduleManager
	 * @param scheme
	 */
	public void initTasks(ScheduleScheme scheme) {
		Map<String, SPartTask> partTaskMap = getPartTasks(scheme);
		Map<String, SOperationTask> operationTaskMap = getOperationTaskS(scheme);
		Map<String, SOperationLink> operationLinkMap = getOperationLinks(scheme);

		List<SOperationTask> cooperationTaskList = new ArrayList<SOperationTask>();// getCooperateTaskList(scheme);

		for (SOperationTask operationTask : operationTaskMap.values()) {
			String parentTaskUid = operationTask.getParentTaskUid();
			if (partTaskMap.containsKey(parentTaskUid)) {
				SPartTask parentTask = partTaskMap.get(parentTaskUid);
				operationTask.setParentTask(parentTask);
				parentTask.getOperationTaskList().add(operationTask);
			} else {
				
			}
		}

		// List<SPartTask> partTaskWithoutOperTasksList = new
		// ArrayList<SPartTask>();
		// for (SPartTask partTask : partTaskList) {
		//
		// if (partTask.getOperationTaskList().size() == 0) {
		// partTaskWithoutOperTasksList.add(partTask);
		// }
		// else
		// partTask.sortByOperationId();
		// }
		// partTaskList.removeAll(partTaskWithoutOperTasksList);

		// create the links between the operations
		// for (SOperationLink operationLink : operationLinkMap.values()) {
		// String predTaskUid = operationLink.getPredecessorUid();
		// String succTaskUid = operationLink.getSuccessorUid();
		// SOperationTask predTask = null;
		// SOperationTask succTask = null;
		// if (operationTaskMap.containsKey(predTaskUid)) {
		// predTask = operationTaskMap.get(predTaskUid);
		// }
		// if (operationTaskMap.containsKey(succTaskUid)) {
		// succTask = operationTaskMap.get(succTaskUid);
		// }
		// if (predTask != null && succTask != null) {
		// operationLink.setPredOperationTask(predTask);
		// operationLink.setSuccOperationTask(succTask);
		// predTask.getSuccLinkSet().add(operationLink);
		// succTask.getPredLinkSet().add(operationLink);
		// }
		// }

		for (SOperationTask cooperateTask : cooperationTaskList) {
			cooperateTask.setScheme(scheme);
		}
		// add an operation link between the sequence operations if there don't
		// exist one
		// if the data is correct, this is not necessary
		// for (SPartTask partTask : partTaskList) {
		// List<SOperationTask> opList = partTask.getOperationTaskList();
		// for (int i = 1; i < opList.size(); i++) {
		// SOperationTask opTask = opList.get(i);
		// if (opTask.getPredLinkSet().size() == 0) {
		// SOperationLink operationLink = new SOperationLink();
		// operationLink.setPredecessorUid(opList.get(i - 1)
		// .getTaskUid());
		// operationLink.setSuccessorUid(opTask.getTaskUid());
		// operationLink.setLinkLag(0);
		// operationLink.setIsIneffective(1);
		// operationLink.setLockLevel(0);
		// operationLink.setLinkQty(opTask.getPlanQty());
		// operationLink.setLinkType(1);
		// operationLink.setPredOperationTask(opList.get(i - 1));
		// operationLink.setSuccOperationTask(opTask);
		// opTask.getPredLinkSet().add(operationLink);
		// opList.get(i - 1).getSuccLinkSet().add(operationLink);
		// }
		// }
		// }

		scheme.setAllPartTaskMap(partTaskMap);

	}
	
	/**
	 * @see the method use for the above method 'initTasks'
	 * @see note there have use DBhandler 
	 * @param scheme
	 * @return
	 */
	private Map<String, SPartTask> getPartTasks(ScheduleScheme scheme) {
		Map<String, SPartTask> partTaskMap = scheme.getAllPartTaskMap();
		String deptId = scheme.getDeptUid();
		DBHandler dbHandler = new DBHandler();
		String sqlPartTask = "select t.taskuid," + " t.taskname," + " t.part_number, " + " bpm.drawingid,"
				+ " bpm.part_name," + " t.model," + " t.earlystart," + " t.latefinish," + " t.planstart,"
				+ " t.planfinish," + " t.batchnum," + " bpm.plangrade," + " t.priority," + " t.locked," + " t.planqty,"
				+ " t.deptid," + " d.deptname," + " t.taskstate," + " (select nvl(sum(tl.linkqty),0) "
				+ " from t_links tl " + " where tl.preduid=t.taskuid and tl.dependtype=1) " + " as demandlinkqty"
				+ " from t_tasks t " + " inner join b_part_number bpm " + " on t.part_number = bpm.part_number"
				+ " inner join r_dept d " + " on t.deptid = d.deptid" + " where t.tasktype like '1%' "
				+ " and t.taskstate<106 and t.taskstate>101 " + " and t.mastershop like ? || '%' "
				+ " and t.suspended = 0" + " and t.planqty>0 "
				+ " order by t.priority,bpm.plangrade desc,t.latefinish ";
		log.debug(sqlPartTask);
		try {
			dbHandler.createPreparedStatement(sqlPartTask);
			dbHandler.stmt.setString(1, deptId);

			ResultSet rs = dbHandler.getResultSet();
			while (rs.next()) {
				SPartTask partTask = new SPartTask();
				partTask.setTaskUid(rs.getString("taskuid"));
				partTask.setTaskName(rs.getString("taskname"));
				partTask.setDrawingId(rs.getString("drawingid"));
				partTask.setPartName(rs.getString("part_name"));
				partTask.setPartUid(rs.getString("part_number"));
				partTask.setModel(rs.getString("model"));
				partTask.setEarlyStart(rs.getDate("earlystart"));
				partTask.setLateFinish(rs.getDate("latefinish"));
				partTask.setPlanStart(rs.getDate("planstart"));
				partTask.setPlanFinish(rs.getDate("planfinish"));
				partTask.setControlStart(partTask.getEarlyStart());
				partTask.setBatchNum(rs.getString("batchnum"));
				partTask.setPlanGrade(rs.getInt("plangrade"));
				partTask.setPriority(rs.getInt("priority"));
				partTask.setLocked(rs.getInt("locked"));
				partTask.setPlanQty(rs.getDouble("planqty"));
				partTask.setTaskState(rs.getInt("taskstate"));
				// partTask.setDemandLinkQty(rs.getInt("demandlinkqty"));

				partTask.setTaskScheduleState(SPartTask.TASKSCHEDULESTATE_WAITING);// 等待被调度
				// partTask.setTransferCount(rs.getInt("planqty"));
				// partTask.setOperationTaskList(new
				// ArrayList<SOperationTask>());
				partTask.setScheme(scheme);
				partTaskMap.put(partTask.getTaskUid(), partTask);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} catch (NamingException e) {
			e.printStackTrace();
		} finally {
			dbHandler.closeStmt();
			dbHandler.close();
		}
		return partTaskMap;
	}

	/**
	 * @see the method use for the above method 'initTasks'
	 * @see note there have use DBhandler 
	 * @param scheme
	 * @return
	 */
	private Map<String, SOperationTask> getOperationTaskS(ScheduleScheme scheme) {
		Map<String, SOperationTask> operationTaskMap = scheme.getAllOperationTaskMap();
		;

		String deptId = scheme.getDeptUid();
		DBHandler dbHandler = new DBHandler();
		String sqlOperationTask = "select " + " t.taskuid," + " t.taskname," + " t.operation_id,"
				+ " t.operation_iddesc," + " t.batchnum," + " t.planqty," + " t.completeqty," + " t.parentuid,"
				+ " t.mastershop," + " d.deptname as mastershopname," + " t.taskstate," + " t.locked,"
				+ " t.earlystart," + " t.latefinish,"
				// + " tsd.schedulestart as planstart, tsd.schedulefinish as
				// planfinish,"
				+ " t.materialstate," + " t.resourcestate," + "t.opuid," + " t.routinestate,"
				+ " mmdn(r.estipretime) as estipretime," + " mmdn(r.estiruntime) as estiruntime," + " t.estitaskwork,"
				+ " t.preoptime," + " t.runtime," + " t.controlstart," + " t.controlfinish," + " t.workcenteruid,"
				+ " rr.resname as workcentername,t.part_number " + " from t_tasks t "
				+ " left join r_resource rr on rr.resuid=t.workcenteruid" + " left join r_dept d "
				+ " on t.mastershop=d.deptid "
				// + " left join t_schedule_detail tsd"
				// + " on t.taskuid=tsd.taskuid and tsd.scheduleuid=? "
				// + " inner join t_assignments a on t.taskuid = a.taskuid and
				// a.assntype=1 "
				+ " left join b_routine r on t.opuid = r.uniqueid " + " where t.parentuid in "
				+ " (select tt.taskuid from t_tasks tt "
				+ " where tt.tasktype like '1%' and tt.taskstate<106 and tt.planqty>0    and tt.suspended=0  "
				// + " and exists(select * from t_tasks o where
				// o.parentuid=tt.taskuid and o.taskstate<209 and o.mastershop
				// like ? || '%') "
				+ " and tt.taskstate>101 and tt.mastershop like ?|| '%'" + " and tt.suspended = 0)"
				+ " and t.taskstate<209 " + " order by t.parentuid, t.operation_id";
		log.debug(sqlOperationTask);
		try {
			dbHandler.createPreparedStatement(sqlOperationTask);
			dbHandler.stmt.setString(1, deptId);

			ResultSet rs = dbHandler.getResultSet();
			while (rs.next()) {
				SOperationTask operationTask = new SOperationTask();
				operationTask.setTaskUid(rs.getString("taskuid"));
				operationTask.setTaskName(rs.getString("taskname"));
				operationTask.setOperationId(rs.getFloat("operation_id"));
				operationTask.setOperationIdDesc(rs.getString("operation_iddesc"));
				operationTask.setOpUid(rs.getString("opuid"));
				operationTask.setBatchNum(rs.getString("batchnum"));
				operationTask.setPlanQty(rs.getDouble("planqty"));
				operationTask.setCompleteQty(rs.getDouble("completeqty"));
				operationTask.setParentTaskUid(rs.getString("parentuid"));
				operationTask.setLocked(rs.getInt("locked"));
				operationTask.setMasterShop(rs.getString("mastershop"));
				operationTask.setMasterShopName(rs.getString("mastershopname"));
				int taskstate = rs.getInt("taskstate") < 205 ? 205 : rs.getInt("taskstate");
				if (taskstate == 206) {
					taskstate = 205;
				}
				operationTask.setTaskState(taskstate);
				operationTask.setEarlyStart(rs.getTimestamp("earlystart"));
				operationTask.setLateFinish(rs.getTimestamp("latefinish"));
				// operationTask.setPlanStart(rs.getTimestamp("planstart"));
				// operationTask.setPlanFinish(rs.getTimestamp("planfinish"));

				operationTask.setEstiPreTime(rs.getDouble("estipretime"));
				operationTask.setEstiRunTime(rs.getDouble("estiruntime"));

				// operationTask.setControlStart(rs.getTimestamp("controlstart"));
				operationTask.setDeviceClass(rs.getString("workcenteruid"));
				operationTask.setDeviceClassName(rs.getString("workcentername"));
				// operationTask.setDeviceUid(rs.getString("deviceuid"));
				operationTask.setPredLinkSet(new HashSet<SOperationLink>());
				operationTask.setSuccLinkSet(new HashSet<SOperationLink>());
				// operationTask
				// .setAlterResourceList(new ArrayList<ResourceConstraint>());
				// if (operationTask.getEstiPreTime() == 0
				// && operationTask.getEstiRunTime() == 0) {
				// operationTask.setEstiPreTime(60);
				// operationTask.setEstiRunTime(20);
				// }

				operationTask.setTaskScheduleState(SOperationTask.ASSNSTATE_WAITING);

				operationTask.setPartUid(rs.getString("part_number"));

				operationTask.setScheme(scheme);

				// operationTask.calTaskWork();

				operationTask.setScheme(scheme);
				operationTaskMap.put(operationTask.getTaskUid(), operationTask);

			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (NamingException e) {
			e.printStackTrace();
		} finally {
			dbHandler.closeStmt();
			dbHandler.close();
		}

		return operationTaskMap;
	}
	
	/**
	 * @see the method use for the above method 'initTasks'
	 * @see note there have use DBhandler 
	 * @param scheme
	 * @return
	 */
	private Map<String, SOperationLink> getOperationLinks(ScheduleScheme scheme) {
		Map<String, SOperationLink> operationLinks = scheme.getAllOperationLinkMap();
		String deptId = scheme.getDeptUid();
		DBHandler dbHandler = new DBHandler();
		String sqlOperationLink = "select tl.succuid," + " tl.preduid," + " tl.linkqty,"
				+ " nvl(tl.linklag, 0) as linklag," + " tl.isineffect," + " tl.locklevel," + " tl.UNIQUE_ID,"
				+ " tl.linktype" + " from t_links tl " + " where tl.succuid in "
				+ " (select tt.taskuid from t_tasks tt " + " where tt.parentuid in "
				+ " (select t.taskuid from t_tasks t " + " where t.tasktype like '1%' "
				+ " and t.taskstate<106 and t.taskstate>101 "
				// + " and exists(select * from t_tasks o where
				// o.parentuid=t.taskuid and o.taskstate<209 and o.mastershop
				// like ? || '%') "
				+ " and t.mastershop like ?|| '%' and t.planqty>0    and t.suspended=0  )"
				+ " and tt.taskstate<209 and tt.suspended=0)and tl.dependtype = 0";
		log.debug(sqlOperationLink);
		try {
			dbHandler.createPreparedStatement(sqlOperationLink);
			dbHandler.stmt.setString(1, deptId);
			// dbHandler.stmt.setString(2, deptId);
			ResultSet rs = dbHandler.getResultSet();
			while (rs.next()) {
				SOperationLink operationLink = new SOperationLink();
				operationLink.setLinkUid(rs.getString("UNIQUE_ID"));
				operationLink.setPredecessorUid(rs.getString("preduid"));
				operationLink.setSuccessorUid(rs.getString("succuid"));
				operationLink.setLinkLag(rs.getInt("linklag"));
				operationLink.setIsIneffective(rs.getInt("isineffect"));
				operationLink.setLinkQty(rs.getDouble("linkqty"));
				operationLink.setLinkType(rs.getInt("linktype"));
				operationLink.setScheme(scheme);
				operationLinks.put(operationLink.getLinkKey(), operationLink);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (NamingException e) {
			e.printStackTrace();
		} finally {
			dbHandler.closeStmt();
			dbHandler.close();
		}
		return operationLinks;
	}
	
	/**
	 * @see the method use for ScheduleManager
	 * @param scheme
	 */
	public void openTasks(ScheduleScheme scheme) {
		openPartTaskList(scheme);
		openOperationTasks(scheme);
		openOperationLinks(scheme);
	}
	
	/**
	 * @see the method use for the above method 'openTasks'
	 * @param scheme
	 * @return
	 */
	private Map<String, SPartTask> openPartTaskList(ScheduleScheme scheme) {
		Map<String, SPartTask> partTaskMap = scheme.getAllPartTaskMap();

		String schemeUid = scheme.getScheduleUid();
		DBHandler dbHandler = new DBHandler();
		// String sqlPartTask = "select t.taskuid,"
		// + " t.part_number, "
		// + " t.drawingid,"
		// + " t.part_name,"
		// + " t.model,"
		// + " t.earlystart,"
		// + " t.latefinish,"
		// + " t.planstart,"
		// + " t.planfinish,"
		// + " t.batchnum,"
		// + " t.plangrade,"
		// + " t.priority,"
		// + " t.locked,"
		// + " t.planqty,"
		// + " t.deptid,t.taskstate,t.taskschedulestate ,t.taskscheduletype from
		// t_schedule_parttask t where t.scheduleUid= ? "
		// + " union "
		// + "select t.taskuid,"
		// + " t.part_number, "
		// + " bpm.drawingid,"
		// + " bpm.part_name,"
		// + " t.model,"
		// + " t.earlystart,"
		// + " t.latefinish,"
		// + " t.planstart,"
		// + " t.planfinish,"
		// + " t.batchnum,"
		// + " bpm.plangrade,"
		// + " t.priority,"
		// + " t.locked,"
		// + " t.planqty,"
		// + " t.deptid,"
		// + " t.taskstate,0 as taskschedulestate ,0 as taskscheduletype"
		// + " from t_tasks t inner join b_part_number bpm on
		// t.part_number=bpm.part_number where t.tasktype like '1%' "
		// + " and t.taskstate<106 and t.taskstate>101 and t.mastershop like ?||
		// '%' and t.createtime>? ";
		//

		String sqlPartTask = "select t.taskuid," + " t.part_number, " + " t.drawingid," + " t.part_name," + " t.model,"
				+ " t.earlystart," + " t.latefinish," + " t.planstart," + " t.planfinish," + " t.batchnum,"
				+ " t.plangrade," + " t.priority," + " t.locked," + " t.planqty,"
				+ " t.deptid,t.taskstate,t.taskschedulestate ,t.taskscheduletype from t_schedule_parttask t where t.scheduleUid= ?  "
				+ " order by t.priority,t.plangrade desc,t.latefinish ";
		log.debug("零组件任务更新sql语句" + sqlPartTask);
		try {
			dbHandler.createPreparedStatement(sqlPartTask);
			dbHandler.stmt.setString(1, schemeUid);
			dbHandler.stmt.setString(2, scheme.getDeptUid());
			dbHandler.stmt.setTimestamp(3, getTimeStamp(scheme.getLastUpdateTime()));
			ResultSet rs = dbHandler.getResultSet();
			while (rs.next()) {
				SPartTask partTask = new SPartTask();

				partTask.setTaskUid(rs.getString("taskuid"));
				// partTask.setTaskName(rs.getString("taskname"));
				partTask.setDrawingId(rs.getString("drawingid"));
				partTask.setPartName(rs.getString("part_name"));
				partTask.setPartUid(rs.getString("part_number"));
				partTask.setModel(rs.getString("model"));
				partTask.setEarlyStart(rs.getDate("earlystart"));
				partTask.setLateFinish(rs.getDate("latefinish"));
				partTask.setPlanStart(rs.getDate("planstart"));
				partTask.setPlanFinish(rs.getDate("planfinish"));
				partTask.setControlStart(partTask.getEarlyStart());

				partTask.setBatchNum(rs.getString("batchnum"));
				partTask.setPlanGrade(rs.getInt("plangrade"));
				partTask.setPriority(rs.getInt("priority"));
				partTask.setLocked(rs.getInt("locked"));
				partTask.setPlanQty(rs.getDouble("planqty"));
				partTask.setTaskState(rs.getInt("taskstate"));
				// partTask.setDemandLinkQty(rs.getInt("demandlinkqty"));
				// partTask.setTransferCount(rs.getInt("planqty"));
				partTask.setTaskScheduleState(rs.getInt("taskschedulestate"));
				partTask.setTaskScheduleType(rs.getInt("taskscheduletype"));
				partTask.setScheme(scheme);
				// partTask.setOperationTaskList(new
				// ArrayList<SOperationTask>());
				partTaskMap.put(partTask.getTaskUid(), partTask);

				log.debug("已经导入零件任务：：" + partTask);

			}

		} catch (SQLException e) {
			e.printStackTrace();
		} catch (NamingException e) {
			e.printStackTrace();
		} finally {
			dbHandler.closeStmt();
			dbHandler.close();
		}
		return partTaskMap;
	}
	
	/**
	 * @see the method use for the above method 'openTasks'
	 * @param scheme
	 * @return
	 */
	private Map<String, SOperationTask> openOperationTasks(ScheduleScheme scheme) {
		Map<String, SOperationTask> operationTaskMap = scheme.getAllOperationTaskMap();

		DBHandler dbHandler = new DBHandler();
		// // 先强制完成，再强制不完成的情况没有处理好
		// String sqlOperationTask = "select "
		// + " t.taskuid,"
		// + " t.taskname,"
		// + " t.operation_id,"
		// + " t.operation_iddesc,"
		// + " t.batchnum,"
		// + " t.planqty,"
		// + " ot.completeqty,"// 取最新的完成数量
		// + " t.parentuid,"
		// + " t.mastershop,"
		// + " d.deptname as mastershopname,"
		// + " ot.taskstate,"// 取最新的任务状态
		// + " t.locked,"
		// + " t.earlystart,"
		// + " t.latefinish,"
		// // + " tsd.schedulestart as planstart, tsd.schedulefinish as
		// // planfinish,"
		// + " t.opuid, t.estipretime,"
		// + " t.estiruntime,"
		// + " t.preoptime,"
		// + " t.runtime,"
		// + " t.workcenteruid,"
		// + " rr.resname as
		// workcentername,t.part_number,t.resuid,t.schedulestart,t.schedulefinish,t.TASKSCHEDULETYPE,t.TASKSCHEDULESTATE
		// "
		// + " from t_schedule_detail t "
		// + " inner join t_tasks ot on t.taskuid=ot.taskuid"// inner join //
		// 将删除的同时去掉
		// + " left join r_resource rr on rr.resuid=t.workcenteruid"
		// + " left join r_dept d "
		// + " on t.mastershop=d.deptid "
		// + " where t.scheduleuid=? " // 取工序任务列表
		// + " union "
		// + "select "
		// + " t.taskuid,"
		// + " t.taskname,"
		// + " t.operation_id,"
		// + " t.operation_iddesc,"
		// + " t.batchnum,"
		// + " t.planqty,"
		// + " t.completeqty,"
		// + " t.parentuid,"
		// + " t.mastershop,"
		// + " d.deptname as mastershopname,"
		// + " t.taskstate,"
		// + " t.locked,"
		// + " t.earlystart,"
		// + " t.latefinish,"
		// + " t.opuid, t.estipretime,"
		// + " t.estiruntime,"
		// + " t.preoptime,"
		// + " t.runtime,"
		// + " t.workcenteruid,"
		// + " rr.resname as
		// workcentername,t.part_number,t.resuid,t.schedulestart,t.schedulefinish,t.TASKSCHEDULETYPE,t.TASKSCHEDULESTATE
		// "
		// + " from t_schedule_detail t "
		// + " left join r_resource rr on rr.resuid=t.workcenteruid"
		// + " left join r_dept d " + " on t.mastershop=d.deptid "
		// + " where t.scheduleuid=? and t.TASKSCHEDULETYPE<>"
		// + STask.TASKSCHEDULETYPE_NORMAL // 取调度过程中产生的虚任务
		// + " union select t.taskuid,"
		// + " t.taskname,"
		// + " t.operation_id,"
		// + " t.operation_iddesc,"
		// + " t.batchnum,"
		// + " t.planqty,"
		// + " t.completeqty,"
		// + " t.parentuid,"
		// + " t.mastershop,"
		// + " d.deptname as mastershopname,"
		// + " t.taskstate,"
		// + " t.locked,"
		// + " t.earlystart,"
		// + " t.latefinish,"
		// + "t.opuid,"
		// + " mmdn(r.estipretime) as estipretime,"
		// + " mmdn(r.estiruntime) as estiruntime,"
		// + " t.preoptime,"
		// + " t.runtime,"
		// + " t.workcenteruid,"
		// + " rr.resname as workcentername,t.part_number,null as resuid,null as
		// schedulestart,null as schedulefinish,0 as TASKSCHEDULETYPE,0 as
		// TASKSCHEDULESTATE "
		// + " from t_tasks t "
		// + " left join r_resource rr on rr.resuid=t.workcenteruid"
		// + " left join r_dept d on t.mastershop=d.deptid "
		// + " left join b_routine r on t.opuid = r.uniqueid "
		// + " where t.tasktype like '2%' and "
		// + " ((select mastershop from t_tasks tt where tt.taskuid=t.parentuid)
		// like ?|| '%'"
		// + " or t.mastershop like ?|| '%' ) and t.taskstate<209 and
		// t.createtime> ? ";

		String sqlOperationTask = "select " + " t.taskuid," + " t.taskname," + " t.operation_id,"
				+ " t.operation_iddesc," + " t.batchnum," + " t.planqty," + " t.completeqty," + " t.parentuid,"
				+ " t.mastershop," + " d.deptname as mastershopname," + " t.taskstate," + " t.locked,"
				+ " t.earlystart," + " t.latefinish,"
				// + " tsd.schedulestart as planstart, tsd.schedulefinish as
				// planfinish,"
				+ " t.opuid, t.estipretime," + " t.estiruntime," + " t.estitaskwork," + " t.preoptime," + " t.runtime,"
				+ " t.workcenteruid,"
				+ " rr.resname as workcentername,t.part_number,t.resuid,t.schedulestart,t.schedulefinish "
				+ " from t_schedule_detail t " + " left join r_resource rr on rr.resuid=t.workcenteruid"
				+ " left join r_dept d " + " on t.mastershop=d.deptid "
				// + " left join t_schedule_detail tsd"
				// + " on t.taskuid=tsd.taskuid and tsd.scheduleuid=? "
				// + " inner join t_assignments a on t.taskuid = a.taskuid and
				// a.assntype=1 "
				// + " inner join b_routine r on t.opuid = r.uniqueid "
				+ " where t.scheduleuid=?"
				// + " (select tt.taskuid from t_tasks tt "
				// + " where tt.tasktype like '1%' and tt.taskstate<106 "
				// +" and exists(select * from t_tasks o where
				// o.parentuid=tt.taskuid and o.taskstate<209 and o.mastershop
				// like ? || '%') "
				// + " and tt.taskstate>101 and tt.mastershop like ?|| '%'"
				// + " and tt.suspended = 0)"
				// + " and t.taskstate<209 and t.suspended=0"
				+ " order by t.parentuid, t.operation_id";

		log.debug("更新工序任务的Sql语句" + sqlOperationTask);
		try {
			dbHandler.createPreparedStatement(sqlOperationTask);
			// dbHandler.stmt.setString(1, scheme.getScheduleUid());
			dbHandler.stmt.setString(1, scheme.getScheduleUid());
			dbHandler.stmt.setString(2, scheme.getScheduleUid());
			dbHandler.stmt.setString(3, scheme.getDeptUid());
			dbHandler.stmt.setString(4, scheme.getDeptUid());
			dbHandler.stmt.setTimestamp(5, getTimeStamp(scheme.getLastUpdateTime()));
			ResultSet rs = dbHandler.getResultSet();

			while (rs.next()) {
				SOperationTask operationTask = new SOperationTask();
				operationTask.setTaskUid(rs.getString("taskuid"));
				operationTask.setTaskName(rs.getString("taskname"));
				operationTask.setOperationId(rs.getFloat("operation_id"));
				operationTask.setOperationIdDesc(rs.getString("operation_iddesc"));
				operationTask.setOpUid(rs.getString("opuid"));
				operationTask.setBatchNum(rs.getString("batchnum"));
				operationTask.setPlanQty(rs.getDouble("planqty"));
				operationTask.setCompleteQty(rs.getDouble("completeqty"));
				operationTask.setParentTaskUid(rs.getString("parentuid"));
				operationTask.setLocked(rs.getInt("locked"));
				operationTask.setMasterShop(rs.getString("mastershop"));
				operationTask.setMasterShopName(rs.getString("mastershopname"));
				int taskstate = rs.getInt("taskstate");
				operationTask.setTaskState(taskstate);
				operationTask.setEarlyStart(rs.getTimestamp("earlystart"));
				operationTask.setLateFinish(rs.getTimestamp("latefinish"));
				operationTask.setPlanStart(rs.getTimestamp("schedulestart"));
				operationTask.setPlanFinish(rs.getTimestamp("schedulefinish"));

				operationTask.setEstiPreTime(rs.getDouble("estipretime"));
				operationTask.setEstiRunTime(rs.getDouble("estiruntime"));

				// operationTask.setControlStart(rs.getTimestamp("controlstart"));
				// operationTask
				// .setControlFinish(rs.getTimestamp("controlfinish"));
				operationTask.setDeviceClass(rs.getString("workcenteruid"));
				operationTask.setDeviceClassName(rs.getString("workcentername"));
				operationTask.setDeviceUid(rs.getString("resuid"));
				// operationTask.setDeviceUid(rs.getString("deviceuid"));
				operationTask.setPredLinkSet(new HashSet<SOperationLink>());
				operationTask.setSuccLinkSet(new HashSet<SOperationLink>());
				// operationTask
				// .setAlterResourceList(new ArrayList<ResourceConstraint>());
				// if (operationTask.getEstiPreTime() == 0
				// && operationTask.getEstiRunTime() == 0) {
				// operationTask.setEstiPreTime(60);
				// operationTask.setEstiRunTime(20);
				// }
				// operationTask.calTaskWork();

				operationTask.setPartUid(rs.getString("part_number"));

				operationTask.setTaskScheduleState(rs.getInt("taskScheduleState"));
				operationTask.setTaskScheduleType(rs.getInt("taskScheduleType"));
				operationTask.setScheme(scheme);

				operationTaskMap.put(operationTask.getTaskUid(), operationTask);

				log.debug("已经导入工序任务：" + operationTask);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (NamingException e) {
			e.printStackTrace();
		} finally {
			dbHandler.closeStmt();
			dbHandler.close();
		}

		return operationTaskMap;
	}
	
	/**
	 * @see the method use for the above method 'openTasks'
	 * @see 暂时未采用从外面导入新链接 临时使用 默认都是用parttaskmanager中createDefaultLink
	 * @param scheme
	 * @return
	 */
	private Map<String, SOperationLink> openOperationLinks(ScheduleScheme scheme) {
		Map<String, SOperationLink> operationLinkMap = scheme.getAllOperationLinkMap();
		String deptId = scheme.getDeptUid();
		DBHandler dbHandler = new DBHandler();
		String sqlOperationLink = "select tl.succuid," + " tl.preduid," + " nvl(tl.linklag, 0) as linklag,"
				+ " tl.isineffect," + " tl.linktype" + " from t_schedule_links tl " + " where tl.scheduleuid=? ";

		log.debug(sqlOperationLink);
		try {
			dbHandler.createPreparedStatement(sqlOperationLink);
			dbHandler.stmt.setString(1, scheme.getUuid());

			ResultSet rs = dbHandler.getResultSet();
			while (rs.next()) {
				SOperationLink operationLink = new SOperationLink();
				operationLink.setPredecessorUid(rs.getString("preduid"));
				operationLink.setSuccessorUid(rs.getString("succuid"));
				operationLink.setLinkLag(rs.getInt("linklag"));
				operationLink.setIsIneffective(rs.getInt("isineffect"));
				// operationLink.setLinkQty(rs.getInt("linkqty"));
				operationLink.setLinkType(rs.getInt("linktype"));

				operationLink.setScheme(scheme);
				operationLinkMap.put(operationLink.getLinkKey(), operationLink);

			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (NamingException e) {
			e.printStackTrace();
		} finally {
			dbHandler.closeStmt();
			dbHandler.close();
		}
		return operationLinkMap;
	}
	
	/**
	 * @see the method use for the above method 'openPartTaskList'
	 * @param d
	 * @return
	 */
	private static Timestamp getTimeStamp(Date d) {
		return (d == null ? null : new Timestamp(d.getTime()));
	}
	
	/**
	 * @see the method use for ScheduelManager
	 * @see 还原任务
	 * @param scheme
	 * @throws Exception
	 */
	public void restoreTasks(ScheduleScheme scheme) throws Exception {
		/**
		 * 恢复零件任务
		 */
		Map<String, SPartTask> PartTaskMap = restorePartTaskList(scheme);
		/**
		 * 恢复工序任务
		 */
		/**
		 * @author SnowBear 存入了929条数据，不知道对不对
		 */
		Map<String, SOperationTask> operationTaskMap = restoreOperationTasks(scheme);
		/**
		 * 恢复工序之间的链接关系
		 */

		@SuppressWarnings("unused")
		/**
		 * @author SnowBear 
		 * 存入了1257条数据
		 */
		Map<String, SOperationLink> operationLinkMap = restoreOperationLinks(scheme);
		/**
		 * 建立零件任务与工序任务之间的关系
		 */
		for (SOperationTask operationTask : operationTaskMap.values()) {
			String parentTaskUid = operationTask.getParentTaskUid();
			// 已经完成的工序任务不让进入
			if (PartTaskMap.containsKey(parentTaskUid) && !operationTask.isFinished()) {
				SPartTask parentTask = PartTaskMap.get(parentTaskUid);
				operationTask.setParentTask(parentTask);
				parentTask.getOperationTaskList().add(operationTask);
			} else {
				// 如果任务属于正常任务，而且没有零件任务，就假设该任务完成
				// 2016-05-26
				if (SOperationTask.TASKTYPE_NORMALTASK.equals(operationTask.getTaskType())) {

					// 暂时屏蔽by hba，因为此时有可能只记载了关键零件任务，
					// 一般零件的工序就找不到父任务，原来会将该工序任务置为完成，所以才会发现有的零件没有工序
					// operationTask
					// .setTaskState(SOperationTask.TASKSTATE_COMPLETED);

				}
			}
		}

		// // 初始化协作任务
		// this.restoreCooperateTaskList(scheme);
	}
	
	/**
	 * @see the method use for above method 'restoreTasks'
	 * @param scheme
	 * @return
	 */
	private Map<String, SPartTask> restorePartTaskList(ScheduleScheme scheme) {

		String schemeUid = scheme.getScheduleUid();

		Map<String, SPartTask> partTaskMap = scheme.getAllPartTaskMap();

		try {
			List<SPartTask> sPartTaskList = schedulePartTaskDao.getSchedulePartTask(schemeUid);
			for (SPartTask partTask : sPartTaskList) {
				// 保留hba
				partTask.setScheme(scheme);
				partTaskMap.put(partTask.getTaskUid(), partTask);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
		return partTaskMap;
	}
	
	/**
	 * @author SnowBear
	 * @see the method use for above method 'restoreTasks'
	 * @param scheme
	 * @return
	 * @throws Exception
	 */
	private Map<String, SOperationTask> restoreOperationTasks(ScheduleScheme scheme) throws Exception {

		String schemeUid = scheme.getScheduleUid();

		Map<String, SOperationTask> operationTaskMap = scheme.getAllOperationTaskMap();
		int i = 1;
		//Long time1 = System.currentTimeMillis();

		// 查出来了929条数据，("ootaskstate") >= 209 把这个条件放进去直接查了
		try {
			List<SOperationTask> sOperationTaskList = sOperationTaskDao.getScheduleOperationTask(schemeUid);

			// 然后对这些数据进行修改，修改条件，但是条件里面都是联立几张不同的表，却没有对实体进行赋值，所以暂时先不用这几张表
			// 这些属性在SOperatonTask实体中都有对应，因此还是不需要联立这几张表
			for (SOperationTask operationTask : sOperationTaskList) {
				// 因为需要重新判断类型，所以会将list中的对象重新复制给另一个对象，然后再将对象中的数据复制到另一个对象中
				SOperationTask sOperationTask;
				if (operationTask.getTaskScheduleType() == SOperationTask.TASKSCHEDULETYPE_SERIALGROUP) {
					sOperationTask = new SSerialGroup();// 新串行组任务
					scheme.getGroupTaskList().add(sOperationTask);
				} else if (operationTask.getTaskScheduleType() == SOperationTask.TASKSCHEDULETYPE_PARALLELGROUP) {
					sOperationTask = new SParallelGroup();// 新并行组任务
					scheme.getGroupTaskList().add(sOperationTask);
				} else if (operationTask.getTaskType().equals(SOperationTask.TASKTYPE_TEMPTASK)) {
					sOperationTask = new STempOperationTask();// 新成组任务
					scheme.getScheduleTempTaskList().add(sOperationTask);
				} else if (operationTask.getTaskType().equals(SOperationTask.TASKTYPE_COTASK)) {
					sOperationTask = new SCoTask();// 新协作任务
					scheme.getCoTaskMap().put(operationTask.getTaskUid(), sOperationTask);
				} else {
					sOperationTask = new SOperationTask();
				}
				// 然后将operationTask属性全部给复制给sOperationTask
				sOperationTask.setTaskUid(operationTask.getTaskUid());
				if (log.isDebugEnabled()) {
					if (sOperationTask.getTaskUid().equals("6395d2a5-f19c-441a-af03-b884e1ba235c")) {
						log.debug(operationTask);
					}
				}

				sOperationTask.setTaskName(operationTask.getTaskName());
				sOperationTask.setOperationId(operationTask.getOperationId());
				sOperationTask.setOperationIdDesc(operationTask.getOperationIdDesc());
				sOperationTask.setOpUid(operationTask.getOpUid());
				sOperationTask.setBatchNum(operationTask.getBatchNum());
				sOperationTask.setPlanQty(operationTask.getPlanQty());
				sOperationTask.setCompleteQty(operationTask.getCompleteQty());

				sOperationTask.setParentTaskUid(operationTask.getParentTaskUid());
				sOperationTask.setLocked(operationTask.getLocked());
				sOperationTask.setMasterShop(operationTask.getMasterShop());
				sOperationTask.setMasterShopName(operationTask.getMasterShopName());

				sOperationTask.setDeptUid(operationTask.getDeptUid());
				sOperationTask.setDeptName(operationTask.getDeptName());

				sOperationTask.setTaskState(operationTask.getTaskState());
				sOperationTask.setEarlyStart(operationTask.getEarlyStart());
				sOperationTask.setLateFinish(operationTask.getLateFinish());
				sOperationTask.setPlanStart(operationTask.getPlanStart());
				sOperationTask.setPlanFinish(operationTask.getPlanFinish());

				sOperationTask.setActualStart(operationTask.getActualStart());
				sOperationTask.setActualFinish(operationTask.getActualFinish());

				sOperationTask.setPriority(operationTask.getPriority());
				sOperationTask.setSlackFactor(operationTask.getSlackFactor());

				sOperationTask.setEstiPreTime(operationTask.getEstiPreTime());
				sOperationTask.setEstiRunTime(operationTask.getEstiRunTime());
				sOperationTask.setEstiDelayTime(operationTask.getEstiDelayTime());

				sOperationTask.setDeviceClass(operationTask.getWorkCenterUid());
				String device = sOperationTask.getDeviceClass();
				if ("cooperationCenter".equals(sOperationTask.getDeviceClass())) {
					sOperationTask.setDeviceClassName("外协");
					if (sOperationTask.getMasterShop() == null)
						sOperationTask.setMasterShop("WX");
					if (sOperationTask.getMasterShopName() == null)
						sOperationTask.setMasterShopName("外协");

				} else {
					// 联立R_RESOURCE找到resname赋值给workcentername
					String resname = ""; //workCenterDao.getResName(operationTask.getWorkCenterUid());
					// 这里不理解，为什么devicecentername 和 workcentername是一样的
					sOperationTask.setWorkCenterName(resname);
					sOperationTask.setDeviceClassName(resname);
				}

				sOperationTask.setDeviceUid(operationTask.getDeviceUid());
				sOperationTask.setShiftsCount(operationTask.getShiftsCount());

				sOperationTask.setNotes(operationTask.getNotes());
				sOperationTask.setCanSplit(operationTask.getCanSplit());
				sOperationTask.setDeviceSeq(operationTask.getDeviceSeq());
				sOperationTask.setCalUid(operationTask.getCalUid());

				sOperationTask.setPredLinkSet(new HashSet<SOperationLink>());
				sOperationTask.setSuccLinkSet(new HashSet<SOperationLink>());

				sOperationTask.setPartUid(operationTask.getPartUid());
				sOperationTask.setDrawingId(operationTask.getDrawingId());
				sOperationTask.setPartName(operationTask.getPartName());
				sOperationTask.setGroupTaskUid(operationTask.getGroupTaskUid());
				sOperationTask.setTaskScheduleState(operationTask.getTaskScheduleState());
				sOperationTask.setTaskScheduleType(operationTask.getTaskScheduleType());
				sOperationTask.setAssignState(operationTask.getAssignState());

				if (operationTask.getTaskType() == null)
					sOperationTask.setTaskType(SOperationTask.TASKTYPE_NORMALTASK);
				else
					sOperationTask.setTaskType(operationTask.getTaskType());

				sOperationTask.setPlanGrade(operationTask.getPlanGrade());

				sOperationTask.setCoTaskState(operationTask.getCoTaskState());

				sOperationTask.setManualScheduleState(operationTask.getManualScheduleState());

				sOperationTask.setTransferBatchQty(operationTask.getTransferBatchQty());

				// br.PROCESS_BATCH_QUANTITY ,br.PROCESS_BATCH_RUNTIME
				// left join b_routine br on t.opuid=br.uniqueid
				// 将这两个属性传回来
				// 一般步骤：先找到这张表对应的实体,选择Operation
				// 然后在本dao文件中新建OperationDao 一边传入后台建立Session
				String opUid = sOperationTask.getOpUid();
				//Double processBatchQty = operationDao.getProcessBatchQty(opUid);
				//Double processBatchRunTime = operationDao.getProcessBatchRunTime(opUid);
				//sOperationTask.setProcessBatchQty(processBatchQty);
				//sOperationTask.setProcessBatchRunTime(processBatchRunTime);
				// 在查询方法中已经赋值了初值0.0，因此该处的判断条件可以不要
				/*
				 * if (processBatchQty != null)
				 * sOperationTask.setProcessBatchQty(processBatchQty); else
				 * sOperationTask.setProcessBatchQty(0.0);
				 * 
				 * if (processBatchRunTime != null)
				 * sOperationTask.setProcessBatchRunTime(processBatchRunTime);
				 * else sOperationTask.setProcessBatchRunTime(0.0);
				 */

				if (log.isDebugEnabled()) {
					if ("bf6ad62b-8ae3-42ed-8465-1b1ae19480e4".equals(sOperationTask.getTaskUid())) {
						log.debug("aaaaaaaaaaaa");
					}
				}
				sOperationTask.setScheme(scheme);
				operationTaskMap.put(sOperationTask.getTaskUid(), sOperationTask);
			}
			//Long time2 = System.currentTimeMillis();
			//System.out.println("总共需要花费："+(time2-time1)+"ms");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}

		return operationTaskMap;
	}
	
	/**
	 * @author SnowBear
	 * @see the method use for above method 'restoreTasks'
	 * @param scheme
	 * @return 将sql语句修改为session的形式
	 */
	private Map<String, SOperationLink> restoreOperationLinks(ScheduleScheme scheme) {
		Map<String, SOperationLink> operationLinkMap = scheme.getAllOperationLinkMap();
		String deptId = scheme.getDeptUid();
		String scheduleuid = scheme.getScheduleUid();
		try {
			List<SOperationLink> sOperationLinkList = new ArrayList<SOperationLink>();
			sOperationLinkList = sOperationLinkDao.getScheduleOperationLinkList(scheduleuid);

			//for (SOperationLink sOperationLink : sOperationLinkList) {
			//删除的时候如果用高级循环表达式可能会出错,因此改成简单循环式
			for(int i = sOperationLinkList.size()-1;i >= 0 ; i--){
				SOperationLink sOperationLink = sOperationLinkList.get(i);
				if (sOperationLink.getLinkLag() == null) {
					sOperationLink.setLinkLag(0);
				}
				// 和t_schedule_detail表内联，然后删除一些值，主要问题是inner join
				// 解决方法，通过两个属性传回到SOperationTask中，然后get回来的对象如果是空的，那么就将这个
				// sOperationLink对象给删除，不然就保留 snowbear
				String predecessorUid = sOperationLink.getPredecessorUid();// =tsd.taskuid
				String scheduleUid = sOperationLink.getScheduleUid();// =tsd.scheduleuid
				SOperationTask sOperationTask = scheme.getAllOperationTaskMap().get(predecessorUid);
				if (sOperationTask == null) {
					//sOperationLinkList.remove(i);
					continue;
				}

				//多了这么一层判断之后就是要将所有的属性重新赋值一边，snowbear
				//在数据苦衷查询之后发现里面的所有的值都是0和null，没有1的形式
				//因此建议去掉这个判断语句，以及后面的赋值语句，直接将sOperationLink对象存入map
				/*SOperationLink operationLink;
				if(sOperationLink.getVirtualLink() == true){
					operationLink = new SVirtualLink();
				} else {
					operationLink = new SOperationLink();
				}
				operationLink.setPersistence(true);
				operationLink.setLinkUid(rs.getString("LINKUID"));
				operationLink.setPredecessorUid(rs.getString("preduid"));
				operationLink.setSuccessorUid(rs.getString("succuid"));
				operationLink.setLinkLag(rs.getInt("linklag"));
				operationLink.setLocked(rs.getBoolean("locked"));
				operationLink.setLinkType(rs.getInt("linktype"));
				operationLink.setMoveType(rs.getInt("moveType"));
				operationLink.setTransferQty(rs.getInt("TRANSFER_QTY"));
				operationLink.setDependType(rs.getInt("dependType"));
				operationLink.setCreatorUid(rs.getString("CREATOR"));
				operationLink.setCreateTime(rs.getTimestamp("CREATETIME"));
				operationLink.setNotes(rs.getString("NOTES"));
				operationLink.setScheme(scheme);*/
				//linkkey是一个复合主键 snowbear
				sOperationLink.setScheme(scheme);
				operationLinkMap.put(sOperationLink.getLinkKey(), sOperationLink);

			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
		return operationLinkMap;
	}
	
	/**
	 * @see the method use for ScheduelManager
	 * @param baseScheme
	 * @return
	 * @throws BaseDBException
	 */
	public List<SOperationTask> getBaseScheduleOperationTaskList(ScheduleScheme baseScheme) throws BaseDBException {

		List<SOperationTask> operationTaskList = new ArrayList<SOperationTask>();
		String deptId = baseScheme.getDeptUid();
		DBHandler dbHandler = new DBHandler();
		String sqlOperationTask = "select t.* " + " from t_schedule_detail t "
				+ " left join r_resource r on r.resuid=t.resuid"
				+ " left join  t_schedule_parttask tsp on t.parentuid=tsp.taskuid and tsp.scheduleuid=? "
				+ " where  t.scheduleuid=? ";
		if (baseScheme.getPartCriticalLevel() != null)
			sqlOperationTask += " and tsp.ISCRITICAL>=" + baseScheme.getPartCriticalLevel();
		if (baseScheme.getCriticalLevel() != null)
			;
		sqlOperationTask += " and r.CRITICAL_LEVEL<=" + baseScheme.getCriticalLevel();
		log.debug(sqlOperationTask);
		try {
			dbHandler.createPreparedStatement(sqlOperationTask);
			dbHandler.stmt.setString(1, baseScheme.getScheduleUid());
			dbHandler.stmt.setString(2, baseScheme.getScheduleUid());

			ResultSet rs = dbHandler.getResultSet();
			while (rs.next()) {
				SOperationTask operationTask = new SOperationTask();
				operationTask.setTaskUid(rs.getString("taskuid"));

				operationTask.setPlanStart(rs.getTimestamp("SCHEDULESTART"));
				operationTask.setPlanFinish(rs.getTimestamp("SCHEDULEFINISH"));
				operationTask.setDeviceUid(rs.getString("RESUID"));

				//
				//
				// //
				// operationTask.setControlStart(rs.getTimestamp("controlstart"));
				// operationTask.setDeviceClass(rs.getString("workcenteruid"));
				// operationTask
				// .setDeviceClassName(rs.getString("workcentername"));
				// operationTask.setDeviceUid(rs.getString("deviceuid"));

				// operationTask
				// .setAlterResourceList(new ArrayList<ResourceConstraint>());
				// if (operationTask.getEstiPreTime() == 0
				// && operationTask.getEstiRunTime() == 0) {
				// operationTask.setEstiPreTime(60);
				// operationTask.setEstiRunTime(20);
				// }

				operationTask.setPartUid(rs.getString("part_number"));
				operationTask.setBatchNum(rs.getString("batchNum"));
				operationTask.setOperationIdDesc(rs.getString("OPERATION_IDDESC"));

				operationTaskList.add(operationTask);

			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (NamingException e) {
			e.printStackTrace();
		} finally {
			dbHandler.closeStmt();
			dbHandler.close();
		}

		return operationTaskList;
	}
	
	/**
	 * @see the method use for ScheduelManager
	 * @param schemeUid
	 * @param newScheduleUid
	 * @return
	 * @throws Exception
	 */
	public boolean exportScheduleScheme(String schemeUid, String newScheduleUid) throws Exception {

		// String newScheduleUid = IdentityGenerator.GetIdentityUUID();

		DBHandler dbHandler = new DBHandler();

		try {
			String sql;
			// sql = "insert into t_schedule_header(SCHEDULEUID, SCHEDULENAME,
			// SCHEDULESTATE, SCHEDULETYPE, CREATOR, "
			// + "CREATETIME, NOTES, COMPLETEPERCENT, DEPTID, CHECKTIME,
			// SCHEDULESTART, SCHEDULEFINISH, SCHEDULEINTERVAL,"
			// + " ITERCOUNT, AUTOPS, CRITICAL_LEVEL, LATEFINISH, UTILIZEDAYS,
			// CONVERSESLACK, MINSPLITSLACK, "
			// + "ALLOW_INIT_SPLIT, ALLOW_LEVEL_SPLIT, SDSCOST, MAXOVERLAP,
			// ISINEFFECT, ALLOWAUTOOVERTIME, MINSHIPLAG,"
			// + " OVERTIMESLACK, ALLOWAUTOPS, ALLOWWORKCENTERREP, ALLOWGROUP,
			// GROUPDELIVERYDIFF, LOCKLEVEL, AUTOPSSLACK,"
			// + " ALLOWCOMPRESSNET, COMPRESSNETSLACK, ALLOWWRITELOG, ASSNDATE,
			// DISPATCHDATE, MAXSHIPLAG, LOCKREADYTASK,"
			// + " LOCKDISPATCHTASK, IGNORESETUPFORMW, DATAIMPORTED,
			// ALLOWOVERTIMEUBOUND, OVERTIMEUBOUND, PSTASKLEVEL,"
			// + " OVERTIMETASKLEVEL,"
			// + " WARNINGWAITDAYS, SLACKFACTOR, WATCHDAYS, PLANSTART,
			// PLANFINISH, LAST_UPDATE_TIME, DEFAULT_CALENDAR_UID, "
			// + "ALLOW_AUTO_REGRESS_HOUR, DISPATCH_DAYS, ALLOW_OVERWRITE_SHIFT,
			// SHIFT_PRODUCTION_OVERTIME, SHIFT_PRODUCTION_FREETIME,"
			// + " ROUNDEDUP, ROUNDEDDOWN, BASE_SCHEDULE_UID,SCHEMETYPE)"
			// + " select ?, ?, SCHEDULESTATE, SCHEDULETYPE, CREATOR, "
			// + "sysdate, NOTES, COMPLETEPERCENT, DEPTID, CHECKTIME,
			// SCHEDULESTART, SCHEDULEFINISH, SCHEDULEINTERVAL, ITERCOUNT, "
			// + "AUTOPS, CRITICAL_LEVEL, LATEFINISH, UTILIZEDAYS,
			// CONVERSESLACK, MINSPLITSLACK, ALLOW_INIT_SPLIT,
			// ALLOW_LEVEL_SPLIT,"
			// + " SDSCOST, MAXOVERLAP, ISINEFFECT, ALLOWAUTOOVERTIME,
			// MINSHIPLAG, OVERTIMESLACK, ALLOWAUTOPS, ALLOWWORKCENTERREP, "
			// + "ALLOWGROUP, GROUPDELIVERYDIFF, LOCKLEVEL, AUTOPSSLACK,
			// ALLOWCOMPRESSNET, COMPRESSNETSLACK, ALLOWWRITELOG, ASSNDATE,"
			// + " DISPATCHDATE, MAXSHIPLAG, LOCKREADYTASK, LOCKDISPATCHTASK,
			// IGNORESETUPFORMW, DATAIMPORTED, ALLOWOVERTIMEUBOUND,"
			// + " OVERTIMEUBOUND, PSTASKLEVEL, OVERTIMETASKLEVEL,
			// WARNINGWAITDAYS, "
			// + "SLACKFACTOR, WATCHDAYS, PLANSTART, PLANFINISH,
			// LAST_UPDATE_TIME, DEFAULT_CALENDAR_UID, ALLOW_AUTO_REGRESS_HOUR,"
			// + " DISPATCH_DAYS, ALLOW_OVERWRITE_SHIFT,
			// SHIFT_PRODUCTION_OVERTIME, SHIFT_PRODUCTION_FREETIME, ROUNDEDUP,
			// ROUNDEDDOWN, "
			// + "BASE_SCHEDULE_UID ,SCHEMETYPE from t_schedule_header where
			// scheduleUid=? ";
			//
			// dbHandler.createPreparedStatement(sql);
			// dbHandler.stmt.setString(1, newScheduleUid);
			// dbHandler.stmt.setString(2, newScheduleName);
			// dbHandler.stmt.setString(3, schemeUid);
			// dbHandler.executeUpdate();

			sql = "insert into t_schedule_parttask (SCHEDULEUID,TASKUID,EARLYSTART,LATEFINISH,PLANSTART,PLANFINISH,PRIORITY,DEPTID,PSDURATION,REMAINWORK,REMAIN_CRITICAL_WORK,ISSUCCESS,LOCKED,PART_NUMBER,BATCHNUM,TASKSTATE,PLANQTY,DRAWINGID,ISSPLITTED,SLACKFACTOR,PART_NAME,MODEL,PLANGRADE,TASKSCHEDULESTATE,TASKSCHEDULETYPE,NOTES,DELAYCOST,ISCRITICAL) "
					+ "  select ?,TASKUID,EARLYSTART,LATEFINISH,PLANSTART,PLANFINISH,PRIORITY,DEPTID,PSDURATION,REMAINWORK,REMAIN_CRITICAL_WORK,ISSUCCESS,LOCKED,PART_NUMBER,BATCHNUM,TASKSTATE,PLANQTY,DRAWINGID,ISSPLITTED,SLACKFACTOR,PART_NAME,MODEL,PLANGRADE,TASKSCHEDULESTATE,TASKSCHEDULETYPE,NOTES,DELAYCOST,ISCRITICAL "
					+ " from t_schedule_parttask where scheduleuid=?";
			dbHandler.createPreparedStatement(sql);
			dbHandler.stmt.setString(1, newScheduleUid);
			dbHandler.stmt.setString(2, schemeUid);
			dbHandler.executeUpdate();

			sql = "insert into t_schedule_detail (SCHEDULEUID, TASKUID, PLANQTY, CREATOR, CREATETIME, SCHEDULESTART,"
					+ " SCHEDULEFINISH, RESUID, NOTES, DEPTID, BASESTART, BASEFINISH, PRIORITY, CONSTRAINTTYPE, "
					+ "CONSTRAINTDATE, WORKCENTERUID, ESTITASKWORK, OLDWORKCENTERUID, ESTIPRETIME, ESTIRUNTIME, LOCKED, "
					+ "PART_NUMBER, BATCHNUM, OPERATION_ID, OPERATION_IDDESC, ISSUCCESS, EARLYSTART, LATEFINISH, "
					+ "COMPLETEQTY, PARENTUID, TASKSTATE, PREOPTIME, RUNTIME, STARTENDMARK, NEEDPREPARE, LINKLAG,"
					+ " MASTERSHOP, ISINEFFECT, TASKSCHEDULESTATE, OPUID, TASKNAME, SLACKFACTOR, LATESTARTSEGEMENT,"
					+ " PREPAREREADY, SHIFTS_COUNT, ACTUALSTART, ACTUALFINISH, ACTUA_LSHIFTS_COUNT, VIOLATE_REASON, "
					+ "TASKSCHEDULETYPE, ACTUAL_PREPARE_FINISH, ACTUAL_FIRST_FINISH, CANSPLIT, DEVICESEQ, CAL_UID,"
					+ " GROUP_TASKUID, ASSIGNSTATE, TASKTYPE, COTASKSTATE, COSCHEDULESTART, COSCHEDULEFINISH) "
					+ "  select ?, TASKUID, PLANQTY, CREATOR, sysdate, SCHEDULESTART, SCHEDULEFINISH, RESUID, NOTES,"
					+ " DEPTID, BASESTART, BASEFINISH, PRIORITY, CONSTRAINTTYPE, CONSTRAINTDATE, WORKCENTERUID, ESTITASKWORK, "
					+ "OLDWORKCENTERUID, ESTIPRETIME, ESTIRUNTIME, LOCKED, PART_NUMBER, BATCHNUM, OPERATION_ID, OPERATION_IDDESC,"
					+ " ISSUCCESS, EARLYSTART, LATEFINISH, COMPLETEQTY, PARENTUID, TASKSTATE, PREOPTIME, RUNTIME, STARTENDMARK, "
					+ "NEEDPREPARE, LINKLAG, MASTERSHOP, ISINEFFECT, TASKSCHEDULESTATE, OPUID, TASKNAME, SLACKFACTOR, LATESTARTSEGEMENT,"
					+ " PREPAREREADY, SHIFTS_COUNT, ACTUALSTART, ACTUALFINISH, ACTUA_LSHIFTS_COUNT, VIOLATE_REASON, TASKSCHEDULETYPE, ACTUAL_PREPARE_FINISH,"
					+ " ACTUAL_FIRST_FINISH, CANSPLIT, DEVICESEQ, CAL_UID, GROUP_TASKUID, ASSIGNSTATE, TASKTYPE, COTASKSTATE, COSCHEDULESTART, COSCHEDULEFINISH "
					+ " from t_schedule_detail where scheduleuid=?";
			dbHandler.createPreparedStatement(sql);
			dbHandler.stmt.setString(1, newScheduleUid);
			dbHandler.stmt.setString(2, schemeUid);
			dbHandler.executeUpdate();

			sql = "insert into t_schedule_links (SCHEDULEUID,SUCCUID,PREDUID,LINKTYPE,LINKLAG,PARENTUID,DEPTID,LINKUID,ISDIRTY,ISINEFFECT,DEPENDTYPE,RECORDSTATE,MOVETYPE,TRANSFER_QTY,LOCKED,VIRTUALLINK,CREATOR,CREATETIME,NOTES) "
					+ "  select ?,SUCCUID,PREDUID,LINKTYPE,LINKLAG,PARENTUID,DEPTID,? || '_' ||rownum ,ISDIRTY,ISINEFFECT,DEPENDTYPE,RECORDSTATE,MOVETYPE,TRANSFER_QTY,LOCKED,VIRTUALLINK,CREATOR,sysdate,NOTES "
					+ " from t_schedule_links where scheduleuid=?";
			dbHandler.createPreparedStatement(sql);
			dbHandler.stmt.setString(1, newScheduleUid);
			dbHandler.stmt.setString(2, newScheduleUid);
			dbHandler.stmt.setString(3, schemeUid);
			dbHandler.executeUpdate();

		} finally {
			dbHandler.closeStmt();
			dbHandler.close();
		}

		return true;
	}
	
	/**
	 * @see the method use for ScheduelManager
	 * @param newScheme
	 * @throws Exception
	 */
	public void ScheduleSchemeBaseFilter(ScheduleScheme newScheme) throws Exception {

		DBHandler dbHandler = new DBHandler();
		String sql = "";
		// 概要计划
		if (newScheme.getSchemeType().equals("0")) {
			sql = " update t_schedule_parttask tsp "
					+ " set tsp.TASKSCHEDULESTATE=( case when tsp.ISCRITICAL<?  then 0  else 1 end ) "
					+ " where  tsp.scheduleuid=? and  tsp.TASKSCHEDULESTATE>=0";
			try {
				dbHandler.createPreparedStatement(sql);
				dbHandler.stmt.setInt(1, newScheme.getPartCriticalLevel());
				dbHandler.stmt.setString(2, newScheme.getScheduleUid());
				dbHandler.stmt.execute();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (NamingException e) {
				e.printStackTrace();
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			} finally {
				dbHandler.closeStmt();
				dbHandler.close();
			}

		}

		else if (newScheme.getSchemeType().equals("1")) {
			sql = " update t_schedule_parttask tsp "
					+ " set tsp.TASKSCHEDULESTATE=( case when tsp.ISCRITICAL<? or  tsp.PLANSTART>?  then 0  else 1 end ) "
					+ " where  tsp.scheduleuid=? and  tsp.TASKSCHEDULESTATE>=0";
			try {
				java.sql.Date date = new java.sql.Date(newScheme.getScheduleFinish().getTime());
				dbHandler.createPreparedStatement(sql);
				dbHandler.stmt.setInt(1, newScheme.getPartCriticalLevel());
				dbHandler.stmt.setDate(2, date);
				dbHandler.stmt.setString(3, newScheme.getScheduleUid());
				dbHandler.stmt.execute();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (NamingException e) {
				e.printStackTrace();
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			} finally {
				dbHandler.closeStmt();
				dbHandler.close();
			}
		}

		log.debug(sql);

	}

	/**
	 * @see the method use for ScheduelManager
	 * @param schemeUid
	 * @return
	 * @throws Exception
	 */
	public boolean clearScheduelData(String schemeUid) throws Exception {

		// String newScheduleUid = IdentityGenerator.GetIdentityUUID();

		DBHandler dbHandler = new DBHandler();

		try {
			String sql;
			sql = "delete from t_schedule_parttask where scheduleuid=?";
			dbHandler.createPreparedStatement(sql);
			dbHandler.stmt.setString(1, schemeUid);
			dbHandler.executeUpdate();

			sql = "delete from t_schedule_detail  where scheduleuid=?";
			dbHandler.createPreparedStatement(sql);
			dbHandler.stmt.setString(1, schemeUid);
			dbHandler.executeUpdate();

			sql = "delete from  t_schedule_links  where scheduleuid=?";
			dbHandler.createPreparedStatement(sql);
			dbHandler.stmt.setString(1, schemeUid);
			dbHandler.executeUpdate();

		} finally {
			dbHandler.closeStmt();
			dbHandler.close();
		}

		return true;
	}

	/**
	 * @see the method use for SchedulePartTaskManager
	 * @param partTaskUid
	 * @throws Exception
	 */
	public void removeCompletedPartTak(String partTaskUid) throws Exception {

		DBHandler dbHandler = new DBHandler();
		try {
			String sql = "update t_tasks set text6=1 where taskuid=? and taskstate<106 ";
			log.debug(sql);
			dbHandler.createPreparedStatement(sql);

			dbHandler.stmt.setString(1, partTaskUid);
			dbHandler.executeUpdate();

		} catch (SQLException e) {
			e.printStackTrace();
		} catch (NamingException e) {
			e.printStackTrace();
		} finally {
			dbHandler.closeStmt();
			dbHandler.close();
		}

	}
	
	/**
	 * @see the method use for ScheduelSchemeManager
	 * @param scheme
	 * @param newScheduleName
	 * @param startDate
	 * @param finishDate
	 * @throws Exception
	 */
	public void savePlan(ScheduleScheme scheme, String newScheduleName, Date startDate, Date finishDate)
			throws Exception {
		DBHandler dbHandler = new DBHandler();
		Connection conn = null;

		ScheduleScheme baseLine = new ScheduleScheme();
		String newScheduleUid = IdentityGenerator.GetIdentityString();
		baseLine.setScheduleName(newScheduleName);
		baseLine.setScheduleStart(startDate);
		baseLine.setScheduleFinish(finishDate);
		baseLine.setScheduleUid(newScheduleUid);
		baseLine.setEffective(true);
		PreparedStatement ps = null;

		// added by hba
		PreparedStatement oldpd = null;
		PreparedStatement newpd = null;
		String sqlQueryEquipment = "select tse.scheduleuid,"
				+ "tse.resuid,tse.uniqueid,tse.starttime,tse.finishtime,tse.shift1_worker,tse.shift2_worker,"
				+ "tse.shift3_worker,tse.creator,tse.createtime,tse.notes from t_schedule_equipment tse "
				+ "where tse.scheduleuid=?  ";
		String sqlInsertEquipment = "insert into t_schedule_equipment tse "
				+ "(scheduleuid,resuid,uniqueid,starttime,finishtime,"
				+ "shift1_worker,shift2_worker,shift3_worker,creator,createtime,notes)"
				+ " values(?,?,?,?,?,?,?,?,?,?,?)";
		String oldScheduleUid = scheme.getScheduleUid();
		String oldDeptId = scheme.getDeptUid();
		oldpd = dbHandler.getPreparedStatement(sqlQueryEquipment);

		dbHandler.stmt.setString(1, oldScheduleUid);
		ResultSet oldrs = oldpd.executeQuery();
		newpd = dbHandler.getPreparedStatement(sqlInsertEquipment);
		while (oldrs.next()) {
			dbHandler.stmt.setString(1, newScheduleUid);
			dbHandler.stmt.setString(2, oldrs.getString("resUid"));
			dbHandler.stmt.setString(3, "工段周计划");
			dbHandler.stmt.setDate(4, new java.sql.Date(System.currentTimeMillis()));
			dbHandler.stmt.setDate(5, new java.sql.Date(System.currentTimeMillis()));
			dbHandler.stmt.setString(9, "计划员");
			dbHandler.stmt.setDate(10, new java.sql.Date(System.currentTimeMillis()));
			dbHandler.stmt.setString(11, "");
			if (oldrs.getString("shift1_worker") != null)
				dbHandler.stmt.setString(6, oldrs.getString("shift1_worker"));
			else
				dbHandler.stmt.setString(6, "");
			if (oldrs.getString("shift2_worker") != null)
				dbHandler.stmt.setString(7, oldrs.getString("shift2_worker"));
			else
				dbHandler.stmt.setString(7, "");
			if (oldrs.getString("shift3_worker") != null)
				dbHandler.stmt.setString(8, oldrs.getString("shift3_worker"));
			else
				dbHandler.stmt.setString(8, "");
			// psEquipment.addBatch();
			// psEquipment.executeBatch();
			newpd.executeUpdate();

		}
		newpd.close();
		oldpd.close();
		//

		try {
			conn = dbHandler.getConn();
			// conn.setAutoCommit(false);
			String sqlUpdate = " update t_schedule_header tsh " + " set ISINEFFECT=0 where deptid=? and ISINEFFECT=1";
			dbHandler.createPreparedStatement(sqlUpdate);

			dbHandler.stmt.setString(1, scheme.getDeptUid());
			dbHandler.executeUpdate();

			String sqlInsert = "insert into t_schedule_header tsh "
					+ " (scheduleuid,scheduleName,planstart,planfinish,scheduletype,deptid,creator,createtime,ISINEFFECT)"
					+ "values(?,?,?,?,?,?,?,?,?)";
			dbHandler.createPreparedStatement(sqlInsert);

			dbHandler.stmt.setString(1, newScheduleUid);
			dbHandler.stmt.setString(2, newScheduleName);
			dbHandler.stmt.setTimestamp(3, this.getTimeStamp(startDate));
			dbHandler.stmt.setTimestamp(4, this.getTimeStamp(finishDate));
			dbHandler.stmt.setString(5, "1");
			dbHandler.stmt.setString(6, scheme.getDeptUid());
			dbHandler.stmt.setString(7, scheme.getCreatorUid());
			dbHandler.stmt.setTimestamp(8, this.getTimeStamp(new Date()));
			dbHandler.stmt.setInt(9, 1);

			dbHandler.executeUpdate();

			sqlInsert = "insert into t_schedule_detail td " + " (scheduleuid,taskuid,batchnum,planqty,"
					+ " schedulestart,schedulefinish,earlystart,latefinish,resuid,part_number,opuid,"
					+ " operation_id,operation_iddesc,priority,parentuid,mastershop,workcenteruid,TASKNAME,SHIFTS_COUNT) values"
					+ " (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			ps = dbHandler.getPreparedStatement(sqlInsert);
			for (SOperationTask operationTask : scheme.getAllOperationTaskMap().values()) {

				// if(operationTask.getTaskUid().equals("9aca7f59-8f1e-41bb-a382-99626fa42903"))
				// {
				// System.out.print("");
				// }
				if (!operationTask.isFinished() && operationTask.getAssignState() == SOperationTask.ASSNSTATE_SUCCESS
						&& operationTask.getPlanStart() != null && operationTask.getPlanFinish() != null
						&& operationTask.getPlanStart().after(startDate)
						&& operationTask.getPlanStart().before(finishDate) && operationTask.getGroupTask() == null) {
					{
						// ps = dbHandler.getPreparedStatement(sqlInsert);
						dbHandler.stmt.setString(1, newScheduleUid);
						dbHandler.stmt.setString(2, operationTask.getTaskUid());
						dbHandler.stmt.setString(3, operationTask.getBatchNum());
						dbHandler.stmt.setDouble(4, operationTask.getPlanQty());
						dbHandler.stmt.setTimestamp(5, getTimeStamp(operationTask.getPlanStart()));
						dbHandler.stmt.setTimestamp(6, getTimeStamp(operationTask.getPlanFinish()));
						dbHandler.stmt.setTimestamp(7, getTimeStamp(operationTask.getEarlyStart()));
						dbHandler.stmt.setTimestamp(8, getTimeStamp(operationTask.getLateFinish()));
						dbHandler.stmt.setString(9, operationTask.getDeviceUid());
						dbHandler.stmt.setString(10, operationTask.getPartUid());
						dbHandler.stmt.setString(11, operationTask.getOpUid());
						dbHandler.stmt.setFloat(12, operationTask.getOperationId());
						dbHandler.stmt.setString(13, operationTask.getOperationIdDesc());
						dbHandler.stmt.setString(14, String.valueOf(operationTask.getPriority()).substring(1));
						dbHandler.stmt.setString(15, operationTask.getParentTaskUid());
						dbHandler.stmt.setString(16, operationTask.getMasterShop());
						dbHandler.stmt.setString(17, operationTask.getDeviceClass());
						dbHandler.stmt.setString(18, operationTask.getTaskName());

						dbHandler.stmt.setDouble(19, operationTask.getShiftsCount());
						// dbHandler.stmt.setDouble(19, operationTask
						// .getSlackFactor()==null?);
						// dbHandler.stmt.setDouble(20,
						// operationTask.getLocked());
						ps.addBatch();

						// added by hba
					}

				}
			}

			ps.executeBatch();
			// psEquipment.executeBatch();
			// conn.commit();
			// psEquipment.executeBatch();
			// psEquipment.close();
			ps.close();
			// psEquipment.close();
			// psEquipment.close();
			dbHandler.closeStmt();

		} catch (Exception e) {
			// 一定要采用Exception ,这样任何异常都接住，
			// 而不要采用eclipse自动生成的异常
			// 原先只接住sql exception ,会导致中间某些对象的nullpointer没接住，会导致事务管理失效，数据库中数据丢失
			// 会造成比较严重的问题
			// try {
			// conn.rollback();
			// } catch (SQLException e1) {
			// // TODO Auto-generated catch block
			// e1.printStackTrace();
			// }
			throw e;
		} finally {
			// try {
			// conn.setAutoCommit(true);
			// } catch (SQLException e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }
			dbHandler.closeStmt();
			dbHandler.close();
		}
	}

	/**
	 * @see the method use for ScheduleManager
	 * @param scheme
	 */
	public void validateSchedule(ScheduleScheme scheme) {
		DBHandler dbHandler = new DBHandler();

		String sql = "update t_tasks "
				+ " set (planstart,planfinish,schedulestart,schedulefinish,earlystart,deviceuid)= "
				+ " (select schedulestart,schedulefinish,schedulestart,schedulefinish,earlystart,resuid from  t_schedule_detail"
				+ " where scheduleuid= ? and taskuid=t_tasks.taskuid) "
				+ " where tasktype like '2%' and taskstate<209 and    "
				+ " exists(select * from t_schedule_detail where taskuid=t_tasks.taskuid and scheduleuid= ? and schedulestart is not null and schedulefinish is not null)";
		try {
			dbHandler.createPreparedStatement(sql);
			dbHandler.stmt.setString(1, scheme.getScheduleUid());
			dbHandler.stmt.setString(2, scheme.getScheduleUid());
			dbHandler.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (NamingException e) {
			e.printStackTrace();
		} finally {
			dbHandler.closeStmt();
			dbHandler.close();
		}
	}
	
	/**
	 * @see the method use  for ScheduleSyncManager
	 * @param scheme
	 * @return
	 * @throws Exception
	 */
	public List<SPartTask> getNewPartTask(ScheduleScheme scheme) throws Exception {

		String deptId = scheme.getDeptUid();
		DBHandler dbHandler = new DBHandler();
		List<SPartTask> newPartTaskList = new ArrayList<SPartTask>();

		String sqlPartTask = "select t.taskuid," + " t.taskname," + " t.part_number, " + " bpm.drawingid,"
				+ " bpm.part_name," + " t.model," + " t.earlystart," + " t.latefinish," + " t.planstart,"
				+ " t.planfinish," + " t.batchnum," + " bpm.plangrade," + " t.priority," + " t.locked," + " t.planqty,"
				+ " t.deptid," + " d.deptname," + " t.taskstate "
				// + " (select nvl(sum(tl.linkqty),0) "
				// + " from t_links tl "
				// + " where tl.preduid=t.taskuid and tl.dependtype=1) "
				// + " as demandlinkqty "
				+ " from t_tasks t " + " inner join b_part_number bpm " + " on t.part_number = bpm.part_number"
				+ " inner join r_dept d " + " on t.deptid = d.deptid" + " left join t_schedule_parttask tsp "
				+ " on t.taskuid =tsp.taskuid and tsp.scheduleUid=? " + " where t.tasktype like '1%' "
				+ " and t.taskstate<106 and t.taskstate>101 and tsp.taskuid is null"
				// + " and exists(select * from t_tasks o where
				// o.parentuid=t.taskuid and o.taskstate<209 and o.mastershop
				// like ? || '%') "
				+ " and t.mastershop like ? || '%' " + " and t.suspended = 0" + " and t.planqty>0 ";
		// + " order by t.priority,bpm.plangrade desc,t.latefinish ";
		log.debug("the sql is" + sqlPartTask);
		int iCount = 0;
		try {
			dbHandler.createPreparedStatement(sqlPartTask);
			dbHandler.stmt.setString(1, scheme.getScheduleUid());
			dbHandler.stmt.setString(2, deptId);
			// dbHandler.stmt.setString(3, deptId);
			ResultSet rs = dbHandler.getResultSet();
			while (rs.next()) {

				// 防止出现用户更新后未存盘现象
				String taskUid = rs.getString("taskuid");
				if (scheme.getAllPartTaskMap().containsKey(taskUid))
					continue;

				SPartTask partTask = new SPartTask();
				partTask.setTaskUid(taskUid);
				partTask.setDrawingId(rs.getString("drawingid"));
				partTask.setBatchNum(rs.getString("batchnum"));

				partTask.setTaskName(rs.getString("taskname"));

				partTask.setPartName(rs.getString("part_name"));
				partTask.setPartUid(rs.getString("part_number"));
				partTask.setModel(rs.getString("model"));
				log.debug("earlystart");
				partTask.setEarlyStart(rs.getDate("earlystart"));
				partTask.setLateFinish(rs.getDate("latefinish"));
				log.debug("planstart");
				partTask.setPlanStart(rs.getDate("planstart"));
				partTask.setPlanFinish(rs.getDate("planfinish"));
				partTask.setControlStart(partTask.getEarlyStart());
				partTask.setPlanGrade(rs.getInt("plangrade"));
				log.debug("priority");
				partTask.setPriority(rs.getInt("priority"));
				partTask.setLocked(rs.getInt("locked"));
				log.debug("planqty");
				partTask.setPlanQty(rs.getDouble("planqty"));
				partTask.setTaskState(rs.getInt("taskstate"));
				partTask.setTaskScheduleState(SPartTask.TASKSCHEDULESTATE_WAITING);// 等待被调度
				// partTask.setDemandLinkQty(rs.getInt("demandlinkqty"));
				// partTask.setTransferCount(rs.getInt("planqty"));
				// partTask.setOperationTaskList(new
				// ArrayList<SOperationTask>());

				partTask.setMasterShopUid(scheme.getDeptUid());
				partTask.setDeptUid(scheme.getDeptUid());

				partTask.setScheme(scheme);

				// 用于返回值
				if (newPartTaskList != null)
					newPartTaskList.add(partTask);

				// 在外面同步
				//
				// // 同步工序任务
				// log.debug("同步工序任务");
				// syncOperationTaskByPartTask(scheme, partTask);
				// // 同步工序任务链接关系网络
				// log.debug("同步工序任务链接关系网络");
				// syncOperationLinkByPartTask(scheme, partTask);

				iCount++;

			}

		} catch (SQLException e) {
			throw e;
		} catch (NamingException e) {
			throw e;
		} finally {
			dbHandler.closeStmt();
			dbHandler.close();
		}

		return newPartTaskList;

	}

	/**
	 * @see the method use  for ScheduleSyncManager
	 * @param scheme
	 * @param partTask
	 * @return
	 */
	public Map<String, SOperationTask> syncOperationTaskByPartTask(ScheduleScheme scheme, SPartTask partTask) {
		Map<String, SOperationTask> operationTaskMap = scheme.getAllOperationTaskMap();
		String partTaskUid = partTask.getTaskUid();

		ScheduleOperationTaskManager scheduleOperationTaskManager = SpringUtils.getBean("scheduleOperationTaskManager");

		String deptId = scheme.getDeptUid();
		DBHandler dbHandler = new DBHandler();
		String sqlOperationTask = "select " + " t.taskuid," + " t.taskname," + " t.operation_id,"
				+ " t.operation_iddesc," + " t.batchnum," + " t.planqty," + " t.completeqty," + " t.parentuid,"
				+ " t.mastershop," + " d.deptname as mastershopname," + " t.taskstate," + " t.locked,"
				+ " t.earlystart," + " t.latefinish,"
				// + " tsd.schedulestart as planstart, tsd.schedulefinish as
				// planfinish,"
				+ " t.materialstate," + " t.resourcestate," + "t.opuid," + " t.routinestate,"
				+ " mmdn(r.estipretime) as estipretime," + " mmdn(r.estiruntime) as estiruntime," + " t.estitaskwork,"
				+ " t.preoptime," + " t.runtime," + " t.controlstart," + " t.controlfinish," + " t.workcenteruid,"
				+ " rr.resname as workcentername,t.part_number " + " from t_tasks t "
				+ " left join r_resource rr on rr.resuid=t.workcenteruid" + " left join r_dept d "
				+ " on t.mastershop=d.deptid "
				// + " left join t_schedule_detail tsd"
				// + " on t.taskuid=tsd.taskuid and tsd.scheduleuid=? "
				// + " inner join t_assignments a on t.taskuid = a.taskuid and
				// a.assntype=1 "
				+ " left join b_routine r on t.opuid = r.uniqueid "
				+ " where t.parentuid=? and t.taskstate<209 order by  t.operation_id";
		log.debug(sqlOperationTask);
		try {
			dbHandler.createPreparedStatement(sqlOperationTask);
			dbHandler.stmt.setString(1, partTaskUid);

			ResultSet rs = dbHandler.getResultSet();
			while (rs.next()) {
				SOperationTask operationTask = new SOperationTask();
				operationTask.setTaskUid(rs.getString("taskuid"));
				operationTask.setTaskName(rs.getString("taskname"));
				operationTask.setOperationId(rs.getFloat("operation_id"));
				operationTask.setOperationIdDesc(rs.getString("operation_iddesc"));
				operationTask.setOpUid(rs.getString("opuid"));
				operationTask.setBatchNum(rs.getString("batchnum"));
				operationTask.setPlanQty(rs.getDouble("planqty"));
				operationTask.setCompleteQty(rs.getDouble("completeqty"));
				operationTask.setParentTaskUid(rs.getString("parentuid"));
				operationTask.setLocked(rs.getInt("locked"));

				operationTask.setDeptUid(scheme.getDeptUid());

				operationTask.setMasterShop(rs.getString("mastershop"));
				operationTask.setMasterShopName(rs.getString("mastershopname"));
				int taskstate = rs.getInt("taskstate") < 205 ? 205 : rs.getInt("taskstate");
				if (taskstate == 206) {
					taskstate = 205;
				}
				operationTask.setTaskState(taskstate);
				operationTask.setEarlyStart(rs.getTimestamp("earlystart"));
				operationTask.setLateFinish(rs.getTimestamp("latefinish"));
				// operationTask.setPlanStart(rs.getTimestamp("planstart"));
				// operationTask.setPlanFinish(rs.getTimestamp("planfinish"));

				operationTask.setEstiPreTime(rs.getDouble("estipretime"));
				operationTask.setEstiRunTime(rs.getDouble("estiruntime"));

				// operationTask.setControlStart(rs.getTimestamp("controlstart"));
				operationTask.setTaskScheduleState(SOperationTask.ASSNSTATE_WAITING);
				operationTask.setDeviceClass(rs.getString("workcenteruid"));
				operationTask.setDeviceClassName(rs.getString("workcentername"));
				// operationTask.setDeviceUid(rs.getString("deviceuid"));
				operationTask.setPredLinkSet(new HashSet<SOperationLink>());
				operationTask.setSuccLinkSet(new HashSet<SOperationLink>());
				// operationTask
				// .setAlterResourceList(new ArrayList<ResourceConstraint>());
				// if (operationTask.getEstiPreTime() == 0
				// && operationTask.getEstiRunTime() == 0) {
				// operationTask.setEstiPreTime(60);
				// operationTask.setEstiRunTime(20);
				// }

				operationTask.setPartUid(rs.getString("part_number"));

				operationTask.setScheme(scheme);
				operationTaskMap.put(operationTask.getTaskUid(), operationTask);
				scheduleOperationTaskManager.add(operationTask);

				operationTask.setParentTask(partTask);
				partTask.getOperationTaskList().add(operationTask);

			}
		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			dbHandler.closeStmt();
			dbHandler.close();
		}

		return operationTaskMap;
	}

	/**
	 * @see the method use  for ScheduleSyncManager
	 * @param scheme
	 * @param partTask
	 */
	public void syncOperationLinkByPartTask(ScheduleScheme scheme, SPartTask partTask) {
		String partTaskUid = partTask.getTaskUid();
		Map<String, SOperationLink> operationLinks = scheme.getAllOperationLinkMap();
		// 用全局的operationtask,有点效率不高
		Map<String, SOperationTask> operationTaskMap = scheme.getAllOperationTaskMap();

		ScheduleLinkManager scheduleLinkManager = SpringUtils.getBean("scheduleLinkManager");

		DBHandler dbHandler = new DBHandler();
		String sqlOperationLink = "select tl.succuid," + " tl.preduid," + " tl.linkqty,"
				+ " nvl(tl.linklag, 0) as linklag," + " tl.isineffect," + " tl.locklevel," + " tl.linktype"
				+ " from t_links tl inner join t_tasks t  on tl.preduid=t.taskuid "
				+ " where  t.parentuid=? and t.taskstate<209  and tl.dependtype = 0";
		log.debug(sqlOperationLink);
		try {
			dbHandler.createPreparedStatement(sqlOperationLink);
			dbHandler.stmt.setString(1, partTaskUid);

			ResultSet rs = dbHandler.getResultSet();
			while (rs.next()) {
				SOperationTask predTask = null;
				SOperationTask succTask = null;
				if (operationTaskMap.containsKey(rs.getString("preduid"))) {
					predTask = operationTaskMap.get(rs.getString("preduid"));
				}
				if (operationTaskMap.containsKey(rs.getString("succuid"))) {
					succTask = operationTaskMap.get(rs.getString("succuid"));
				}
				if (predTask != null && succTask != null) {

					scheduleLinkManager.addLink(predTask, succTask, SOperationLink.LINKTYPE_FTS, 0);

				}

			}
		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			dbHandler.closeStmt();
			dbHandler.close();
		}

	}
}
